package ch.unifr.dokpe.htmlpicker.dataformater;

import java.util.*;
import java.lang.reflect.*;
/**
 * Create DataFormater object using the dataformater property
 * <pre>
 * DataFormaterFactory fact = new DataFormaterFactory(Properties properties);
 *</pre>		
 */

public class DataFormaterFactory {

 	private DataFormater[] formaters;
	private Properties properties;

	/* each label string passed in the constructor of the DataFormater is remembered in the labels list*/
	private List<String> labels = new ArrayList<String>();
	
	public DataFormaterFactory(Properties properties){
		this.properties = properties;
		initFormater();
	}

	
	/**
	 * @param  label String label that will select the extracted text that will be formated
	 * @return the formater for the corresponding segement or the last one 
	 */
	public DataFormater getFormater(String label){
		//int last = formaters.length-1;
		if (labels.contains(label) ) {
			int pos = labels.indexOf(label);
			return formaters[pos];
		} else {
			return null;
		}

	}


	private void initFormater(){
	   String allNames =  properties.getProperty("dataFormater");
	   if (allNames != null && allNames.length()>0) {
		String [] clNames =allNames.split(";\\s*");
	  	//labels = new ArrayList();	
		formaters = new DataFormater[clNames.length];
		DataFormater f = null;
		int index = 0;
		for (int i=0; i<clNames.length; i++){
			String clName;	
			String argName;
			try {
			          Class classDefinition; // = Class.forName(clNames[i]);
				  Constructor<?> con;
				  
				  int pos = clNames[i].indexOf("(");
				  if (pos>0) {
					  clName = clNames[i].substring(0,pos);
					  classDefinition = Class.forName(clName);
					  argName = clNames[i].substring(pos+1, clNames[i].length()-1);
					try {	  
					  con = classDefinition.getConstructor(String.class);
					  f = (DataFormater)con.newInstance(argName);
					} catch (InvocationTargetException e){e.printStackTrace();}
					  catch (NoSuchMethodException e){e.printStackTrace();}
					labels.add(argName);
				   
				  } else {throw new RuntimeException("Invalid dataFormater: missing arg");}
				  
				  /** else {
					  
					  clName = clNames[i];
					  classDefinition = Class.forName(clName);
					  f = (DataFormater) classDefinition.newInstance();
					  labels.add("###" + Integer.toString(index++));

				  }
				  */
  			} 
		      	catch (InstantiationException e) {e.printStackTrace();} 
			catch (IllegalAccessException e) {e.printStackTrace();} 
			catch (ClassNotFoundException e) {e.printStackTrace();}
		f.setProperties(properties);	
		formaters[i] = f;
		
		}//for
	   }//if
	}//init
}
//@MITLI@
